package com.ap2;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.ap2.pojo.Musica;

public class Ap2SextaActivity extends Activity {

	static Spinner sp;
	MediaPlayer mediaPlayer = new MediaPlayer();
	ImageButton play, stop, download;
	int a = 0, b = 0, r;
	static String radio = null;
	List<Musica> musicas;
	String[] arrayString; // = {"kjh", "ity", "gjm"};
	Musica musica = new Musica();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		play = (ImageButton) findViewById(R.id.play);
		stop = (ImageButton) findViewById(R.id.stop);
		download = (ImageButton) findViewById(R.id.download);

		sp = (Spinner) findViewById(R.id.radios);
		ArrayAdapter<String> ar = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getRadios());
		ar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(ar);

		play.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (a == 0) {
					starta();
					r = sp.getSelectedItemPosition();
					radio = getLink(r);
					Log.i("IF", "INICIO");
					Log.i("radio", "link..." + radio);
					Log.i("NUMEROOO", "selecionado..." + r);
					mediaPlayer.prepareAsync();
					play.setImageResource(R.drawable.ic_tab_play_selected);
					a = 1;
					Log.i("IF", "FIM");
				} else if (b == 0) {
					Log.i("pause", "Pausada...");
					mediaPlayer.pause();
					play.setImageResource(R.drawable.ic_tab_pause_selected);
					b = 1;
				} else {
					mediaPlayer.start();
					Log.i("buffer", "Continuando...");
					play.setImageResource(R.drawable.ic_tab_play_pause_selected);
					b = 0;
				}

			}
		});

		stop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mediaPlayer.stop();
				mediaPlayer.reset();
				Log.i("Stop", "STOPADO!");
				play.setImageResource(R.drawable.ic_tab_play_unselected);
				a = b = 0;

			}
		});

		download.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {

					new PesquisaAsync().execute();
					
					
//					msgList(arrayString);
					
					
					
					
					
					
					
					
					// tentativas com list e tal....
//					String[] a;
//					a = listaString(musicas);
					
//					Intent troca = new Intent(Ap2SextaActivity.this, ListaSelect.class);
//					Bundle paran = new Bundle();
//					paran.putStringArray("music", arrayString);
//					troca.putExtras(paran);
//					troca.putExtra("music", arrayString);
//					startActivity(troca);
					
				} catch (Exception e) {
					mensagem("Down", "Não foi possivel baixar. " + e.toString());
				}

			}
		});

	}

	public void starta() {
		try {

			r = sp.getSelectedItemPosition();
			Log.i("NUMEROOO", "selecionado..." + r);
			Log.i("radio", "link..." + radio);

			mediaPlayer.setDataSource(getLink(r));
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					mediaPlayer.start();
				}
			});
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getLink(int selecR) {
		switch (selecR) {
		case 0:
			return "http://ouvir.radioblast.com.br:8000";
		case 1:
			return "http://70.36.100.78:9566";
		case 2:
			return "http://radioanimix.no-ip.org:8068";
		default:
			break;
		}
		return null;

	}

	public static String[] getRadios() {
		String[] radio = new String[] { "Blast", "J-Hero", "Animix" };
		return radio;
	}
	
	public void mensagem(String titulo, String texto) {
		AlertDialog.Builder men = new AlertDialog.Builder(Ap2SextaActivity.this);
		men.setTitle(titulo);
		men.setMessage(texto);
		men.setNeutralButton("ok", null);
		men.show();
	}

	public void msgList() {
		AlertDialog.Builder men = new AlertDialog.Builder(Ap2SextaActivity.this);
		
		men.setTitle("Escolha a Música.");
		men.setItems(arrayString, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {

				Log.i("Selecionado..", "selacionado...");
				
			}
		});
		men.show();
		
	}
	
	public static String[] getListMuz(List<Musica> ist) {
		String[] radio = new String[ist.size()];
		for (int i = 0; i < radio.length || i < 6; i++) {
			radio[i] = ist.get(i).getTitulo();
		}
		return radio;

	}

	public void listaString(List<Musica> listaDeMusicas){
		arrayString = new String[listaDeMusicas.size()];
		
		for (int i = 0; i < listaDeMusicas.size(); i++) {
			arrayString[i] = listaDeMusicas.get(i).getTitulo();
		}
	}

	// ............__________-----------------------------------_________----------------------------------............-__-->_.-.

	class PesquisaAsync extends AsyncTask<String, Void, String> {

		private ProgressDialog progressDialog;

		protected void onPreExecute() {
			progressDialog = new ProgressDialog(Ap2SextaActivity.this);
			progressDialog.setMessage("Pesquisando...");
			progressDialog.show();
		}

		protected String doInBackground(String... v) {

			try {
				Log.i("vai", "PESQUISANDO");
				musicas = PesquisaBaixa.buscarMusicaTocada(radio);
				Log.i("vai", "PESQUISADO!!!!!!!!!!!");
				listaString(musicas);

//				musica = musicas.get(0);
//				Log.i("IF", "ENTRAR SE!!!!!!!!!!!");
//				
//				Log.i("vai", "COMEÇAR A BAIXAR");
//				PesquisaBaixa.baixarMusica(musica);
//				Log.i("vai", "BAIXOU!!!");

			} catch (Exception e) {
				progressDialog.dismiss();
				mensagem("Pesquisa Erro", "Falha na pesquisa - Erro: " + e.toString());
			}
			return null;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			msgList();
		}
	}

	class DownloadAsync extends AsyncTask<String, Void, String> {

		private ProgressDialog progressDialog;

		protected void onPreExecute() {
			progressDialog = new ProgressDialog(Ap2SextaActivity.this);
			progressDialog.setMessage("Baixando...");
			progressDialog.show();
		}

		protected String doInBackground(String... v) {

			try {
//				Log.i("vai", "PESQUISANDO");
//				musicas = PesquisaBaixa.buscarMusicaTocada(radio);
//				Log.i("vai", "PESQUISADO!!!!!!!!!!!");
//				listaString(musicas);

//				musica = musicas.get(0);
//				Log.i("IF", "ENTRAR SE!!!!!!!!!!!");
//				
//				Log.i("vai", "COMEÇAR A BAIXAR");
//				PesquisaBaixa.baixarMusica(musica);
//				Log.i("vai", "BAIXOU!!!");

			} catch (Exception e) {
				progressDialog.dismiss();
				mensagem("DownErro", "Falha ao baixar...-> " + musica.getTitulo() + " - Erro: " + e.toString());
			}
			return null;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			mensagem("Download Concluido", "");
		}
	}
	
}